import cgi
import csv
import sys
import logging
from urlparse import urlparse
import random
import gdata.youtube.service
from optparse import OptionParser

#one time function called manually to complete the question with 
#gdata from YT, duration, rating, etc.
class FetchYT():

    def get(self, filename):
        qList = []
        f = open(filename, "r")
        r = csv.DictReader(f)

        for q in r:
          qList.append(q)

        if options.randomize:
          random.shuffle(qList)

        yt_service = gdata.youtube.service.YouTubeService()

        # The YouTube API does not currently support HTTPS/SSL access.
        yt_service.ssl = False

        if options.startIndex == 1:
          #print header
          print("index,type,url,rating,hits,favorites,starttime,endtime,duration,year,title,author,artist,album,category,question,answer,choices,level,misc,vid,playtime,points")

        n=options.startIndex

        for q in qList:

          #VideoClip
          if q['type'] == 'VideoClip':
              if q['url'] == None or q['url'] == '':
                continue

              logging.debug("q url %s" % (q['url']))

              #get vid from url
              a = q['url'].rsplit("v=")
              b = a[1].rsplit("&")
              logging.debug("q vid %s " % b[0])
              q['vid'] = b[0]

              entry = yt_service.GetYouTubeVideoEntry(video_id=q['vid'])

              q['duration'] =  entry.media.duration.seconds
              q['favorites'] = entry.statistics.favorite_count
              q['hits'] = entry.statistics.view_count
              q['rating'] = entry.rating.average
              q['playtime'] = int(q['endtime']) - int(q['starttime'])

              logging.info(q)
     
              if entry.noembed:
                sys.stderr.write("Skipping noembed video: %s\n" % (q['url']))
                continue

          #Question
          elif q['type'] == 'Question':
              q['playtime'] = 3
              q['starttime'] = 0
              q['endtime'] = 0
              q['duration'] = 0
              q['favorites'] = 0
              q['hits'] = 0

          else:
              sys.stderr.write("Skipping Unknown type: %s %s\n" % (q['index'], q['type']))
              continue


          q['points'] = 100;
          q['index'] = n;

          #get the index for the answer from choices
          ch_in = q['choices'].split(',')
          i = 0
          q['answer'] = q['answer'].strip()
          ch_out = ""
          for t in ch_in:
            t1 = t.strip()
            ch_out = ch_out + t1 + ','
            if t1 == q['answer']:
              q['answer'] = i
            i = i+1  

          #if cannot find a matching answer, skip it. Must be some error in the csv
          if type(q['answer']) is not int:
            sys.stderr.write("Choices did not match the answer: %s %s\n" % (q['index'], q['question']))
            continue

          q['choices'] = ch_out.rstrip(',')

          print("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\"%s\",%s,%s,\"%s\",%s,%s,%s,%s,%s" % 
          (
          q['index'], q['type'], q['url'], q['rating'], q['hits'], q['favorites'], q['starttime'], q['endtime'], q['duration'], 
          q['year'], q['title'], q['author'], q['artist'], q['album'], q['category'], q['question'], q['answer'], q['choices'], 
          q['level'], q['misc'], q['vid'], q['playtime'], q['points']
          ))
          
          n = n+1



usage = "%prog [options]"
parser = OptionParser(usage)
parser.add_option("-f", type="string", dest="file", help="CSV file to parse")
parser.add_option("-i", type="int", dest="startIndex", default=1, help="index to start from")
parser.add_option("-R", type="int", dest="randomize", default=0, help="Randomize the output list")

(options, args) = parser.parse_args()

def main():
  #if options.file == None:
      #parser.error("-f: Please specify csv file name")

  f = FetchYT()
  f.get(options.file)


if __name__ == '__main__':
    main()
